1   /*
2    * Copyright (C) 2007 The Guava Authors
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    *
8    * http://www.apache.org/licenses/LICENSE-2.0
9    *
10   * Unless required by applicable law or agreed to in writing, software
11   * distributed under the License is distributed on an "AS IS" BASIS,
12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   * See the License for the specific language governing permissions and
14   * limitations under the License.
15   */
16  
17  package com.google.common.base;
18  
19  import static com.google.common.base.Preconditions.checkNotNull;
20  
21  import com.google.common.annotations.GwtCompatible;
22  
23  import java.io.Serializable;
24  import java.util.ArrayList;
25  import java.util.Arrays;
26  import java.util.Collection;
27  import java.util.List;
28  
29  import javax.annotation.Nullable;
30  
31  /**
32   * Static utility methods pertaining to {@code Predicate} instances.
33   *
34   * <p>All methods returns serializable predicates as long as they're given
35   * serializable parameters.
36   *
37   * <p>See the Guava User Guide article on <a href=
38   * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the
39   * use of {@code Predicate}</a>.
40   *
41   * @author Kevin Bourrillion
42   * @since 2.0 (imported from Google Collections Library)
43   */
44  @GwtCompatible(emulated = true)
45  public final class Predicates {
46    private Predicates() {}
47  
48    // TODO(kevinb): considering having these implement a VisitablePredicate
49    // interface which specifies an accept(PredicateVisitor) method.
50  
51    /**
52     * Returns a predicate that always evaluates to {@code true}.
53     */
54    @GwtCompatible(serializable = true)
55    public static <T> Predicate<T> alwaysTrue() {
56      return ObjectPredicate.ALWAYS_TRUE.withNarrowedType();
57    }
58  
59    /**
60     * Returns a predicate that always evaluates to {@code false}.
61     */
62    @GwtCompatible(serializable = true)
63    public static <T> Predicate<T> alwaysFalse() {
64      return ObjectPredicate.ALWAYS_FALSE.withNarrowedType();
65    }
66  
67    /**
68     * Returns a predicate that evaluates to {@code true} if the object reference
69     * being tested is null.
70     */
71    @GwtCompatible(serializable = true)
72    public static <T> Predicate<T> isNull() {
73      return ObjectPredicate.IS_NULL.withNarrowedType();
74    }
75  
76    /**
77     * Returns a predicate that evaluates to {@code true} if the object reference
78     * being tested is not null.
79     */
80    @GwtCompatible(serializable = true)
81    public static <T> Predicate<T> notNull() {
82      return ObjectPredicate.NOT_NULL.withNarrowedType();
83    }
84  
85    /**
86     * Returns a predicate that evaluates to {@code true} if the given predicate
87     * evaluates to {@code false}.
88     */
89    public static <T> Predicate<T> not(Predicate<T> predicate) {
90      return new NotPredicate<T>(predicate);
91    }
92  
93    /**
94     * Returns a predicate that evaluates to {@code true} if each of its
95     * components evaluates to {@code true}. The components are evaluated in
96     * order, and evaluation will be "short-circuited" as soon as a false
97     * predicate is found. It defensively copies the iterable passed in, so future
98     * changes to it won't alter the behavior of this predicate. If {@code
99     * components} is empty, the returned predicate will always evaluate to {@code
100    * true}.
101    */
102   public static <T> Predicate<T> and(
103       Iterable<? extends Predicate<? super T>> components) {
104     return new AndPredicate<T>(defensiveCopy(components));
105   }
106 
107   /**
108    * Returns a predicate that evaluates to {@code true} if each of its
109    * components evaluates to {@code true}. The components are evaluated in
110    * order, and evaluation will be "short-circuited" as soon as a false
111    * predicate is found. It defensively copies the array passed in, so future
112    * changes to it won't alter the behavior of this predicate. If {@code
113    * components} is empty, the returned predicate will always evaluate to {@code
114    * true}.
115    */
116   public static <T> Predicate<T> and(Predicate<? super T>... components) {
117     return new AndPredicate<T>(defensiveCopy(components));
118   }
119 
120   /**
121    * Returns a predicate that evaluates to {@code true} if both of its
122    * components evaluate to {@code true}. The components are evaluated in
123    * order, and evaluation will be "short-circuited" as soon as a false
124    * predicate is found.
125    */
126   public static <T> Predicate<T> and(Predicate<? super T> first,
127       Predicate<? super T> second) {
128     return new AndPredicate<T>(Predicates.<T>asList(
129         checkNotNull(first), checkNotNull(second)));
130   }
131 
132   /**
133    * Returns a predicate that evaluates to {@code true} if any one of its
134    * components evaluates to {@code true}. The components are evaluated in
135    * order, and evaluation will be "short-circuited" as soon as a
136    * true predicate is found. It defensively copies the iterable passed in, so
137    * future changes to it won't alter the behavior of this predicate. If {@code
138    * components} is empty, the returned predicate will always evaluate to {@code
139    * false}.
140    */
141   public static <T> Predicate<T> or(
142       Iterable<? extends Predicate<? super T>> components) {
143     return new OrPredicate<T>(defensiveCopy(components));
144   }
145 
146   /**
147    * Returns a predicate that evaluates to {@code true} if any one of its
148    * components evaluates to {@code true}. The components are evaluated in
149    * order, and evaluation will be "short-circuited" as soon as a
150    * true predicate is found. It defensively copies the array passed in, so
151    * future changes to it won't alter the behavior of this predicate. If {@code
152    * components} is empty, the returned predicate will always evaluate to {@code
153    * false}.
154    */
155   public static <T> Predicate<T> or(Predicate<? super T>... components) {
156     return new OrPredicate<T>(defensiveCopy(components));
157   }
158 
159   /**
160    * Returns a predicate that evaluates to {@code true} if either of its
161    * components evaluates to {@code true}. The components are evaluated in
162    * order, and evaluation will be "short-circuited" as soon as a
163    * true predicate is found.
164    */
165   public static <T> Predicate<T> or(
166       Predicate<? super T> first, Predicate<? super T> second) {
167     return new OrPredicate<T>(Predicates.<T>asList(
168         checkNotNull(first), checkNotNull(second)));
169   }
170 
171   /**
172    * Returns a predicate that evaluates to {@code true} if the object being
173    * tested {@code equals()} the given target or both are null.
174    */
175   public static <T> Predicate<T> equalTo(@Nullable T target) {
176     return (target == null)
177         ? Predicates.<T>isNull()
178         : new IsEqualToPredicate<T>(target);
179   }
180 
181   /**
182    * Returns a predicate that evaluates to {@code true} if the object reference
183    * being tested is a member of the given collection. It does not defensively
184    * copy the collection passed in, so future changes to it will alter the
185    * behavior of the predicate.
186    *
187    * <p>This method can technically accept any {@code Collection<?>}, but using
188    * a typed collection helps prevent bugs. This approach doesn't block any
189    * potential users since it is always possible to use {@code
190    * Predicates.<Object>in()}.
191    *
192    * @param target the collection that may contain the function input
193    */
194   public static <T> Predicate<T> in(Collection<? extends T> target) {
195     return new InPredicate<T>(target);
196   }
197 
198   /**
199    * Returns the composition of a function and a predicate. For every {@code x},
200    * the generated predicate returns {@code predicate(function(x))}.
201    *
202    * @return the composition of the provided function and predicate
203    */
204   public static <A, B> Predicate<A> compose(
205       Predicate<B> predicate, Function<A, ? extends B> function) {
206     return new CompositionPredicate<A, B>(predicate, function);
207   }
208 
209   // End public API, begin private implementation classes.
210 
211   // Package private for GWT serialization.
212   enum ObjectPredicate implements Predicate<Object> {
213     /** @see Predicates#alwaysTrue() */
214     ALWAYS_TRUE {
215       @Override public boolean apply(@Nullable Object o) {
216         return true;
217       }
218       @Override public String toString() {
219         return "Predicates.alwaysTrue()";
220       }
221     },
222     /** @see Predicates#alwaysFalse() */
223     ALWAYS_FALSE {
224       @Override public boolean apply(@Nullable Object o) {
225         return false;
226       }
227       @Override public String toString() {
228         return "Predicates.alwaysFalse()";
229       }
230     },
231     /** @see Predicates#isNull() */
232     IS_NULL {
233       @Override public boolean apply(@Nullable Object o) {
234         return o == null;
235       }
236       @Override public String toString() {
237         return "Predicates.isNull()";
238       }
239     },
240     /** @see Predicates#notNull() */
241     NOT_NULL {
242       @Override public boolean apply(@Nullable Object o) {
243         return o != null;
244       }
245       @Override public String toString() {
246         return "Predicates.notNull()";
247       }
248     };
249 
250     @SuppressWarnings("unchecked") // safe contravariant cast
251     <T> Predicate<T> withNarrowedType() {
252       return (Predicate<T>) this;
253     }
254   }
255 
256   /** @see Predicates#not(Predicate) */
257   private static class NotPredicate<T> implements Predicate<T>, Serializable {
258     final Predicate<T> predicate;
259 
260     NotPredicate(Predicate<T> predicate) {
261       this.predicate = checkNotNull(predicate);
262     }
263     @Override
264     public boolean apply(@Nullable T t) {
265       return !predicate.apply(t);
266     }
267     @Override public int hashCode() {
268       return ~predicate.hashCode();
269     }
270     @Override public boolean equals(@Nullable Object obj) {
271       if (obj instanceof NotPredicate) {
272         NotPredicate<?> that = (NotPredicate<?>) obj;
273         return predicate.equals(that.predicate);
274       }
275       return false;
276     }
277     @Override public String toString() {
278       return "Predicates.not(" + predicate.toString() + ")";
279     }
280     private static final long serialVersionUID = 0;
281   }
282 
283   private static final Joiner COMMA_JOINER = Joiner.on(',');
284 
285   /** @see Predicates#and(Iterable) */
286   private static class AndPredicate<T> implements Predicate<T>, Serializable {
287     private final List<? extends Predicate<? super T>> components;
288 
289     private AndPredicate(List<? extends Predicate<? super T>> components) {
290       this.components = components;
291     }
292     @Override
293     public boolean apply(@Nullable T t) {
294       // Avoid using the Iterator to avoid generating garbage (issue 820).
295       for (int i = 0; i < components.size(); i++) {
296         if (!components.get(i).apply(t)) {
297           return false;
298         }
299       }
300       return true;
301     }
302     @Override public int hashCode() {
303       // add a random number to avoid collisions with OrPredicate
304       return components.hashCode() + 0x12472c2c;
305     }
306     @Override public boolean equals(@Nullable Object obj) {
307       if (obj instanceof AndPredicate) {
308         AndPredicate<?> that = (AndPredicate<?>) obj;
309         return components.equals(that.components);
310       }
311       return false;
312     }
313     @Override public String toString() {
314       return "Predicates.and(" + COMMA_JOINER.join(components) + ")";
315     }
316     private static final long serialVersionUID = 0;
317   }
318 
319   /** @see Predicates#or(Iterable) */
320   private static class OrPredicate<T> implements Predicate<T>, Serializable {
321     private final List<? extends Predicate<? super T>> components;
322 
323     private OrPredicate(List<? extends Predicate<? super T>> components) {
324       this.components = components;
325     }
326     @Override
327     public boolean apply(@Nullable T t) {
328       // Avoid using the Iterator to avoid generating garbage (issue 820).
329       for (int i = 0; i < components.size(); i++) {
330         if (components.get(i).apply(t)) {
331           return true;
332         }
333       }
334       return false;
335     }
336     @Override public int hashCode() {
337       // add a random number to avoid collisions with AndPredicate
338       return components.hashCode() + 0x053c91cf;
339     }
340     @Override public boolean equals(@Nullable Object obj) {
341       if (obj instanceof OrPredicate) {
342         OrPredicate<?> that = (OrPredicate<?>) obj;
343         return components.equals(that.components);
344       }
345       return false;
346     }
347     @Override public String toString() {
348       return "Predicates.or(" + COMMA_JOINER.join(components) + ")";
349     }
350     private static final long serialVersionUID = 0;
351   }
352 
353   /** @see Predicates#equalTo(Object) */
354   private static class IsEqualToPredicate<T>
355       implements Predicate<T>, Serializable {
356     private final T target;
357 
358     private IsEqualToPredicate(T target) {
359       this.target = target;
360     }
361     @Override
362     public boolean apply(T t) {
363       return target.equals(t);
364     }
365     @Override public int hashCode() {
366       return target.hashCode();
367     }
368     @Override public boolean equals(@Nullable Object obj) {
369       if (obj instanceof IsEqualToPredicate) {
370         IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj;
371         return target.equals(that.target);
372       }
373       return false;
374     }
375     @Override public String toString() {
376       return "Predicates.equalTo(" + target + ")";
377     }
378     private static final long serialVersionUID = 0;
379   }
380 
381   /** @see Predicates#in(Collection) */
382   private static class InPredicate<T> implements Predicate<T>, Serializable {
383     private final Collection<?> target;
384 
385     private InPredicate(Collection<?> target) {
386       this.target = checkNotNull(target);
387     }
388 
389     @Override
390     public boolean apply(@Nullable T t) {
391       try {
392         return target.contains(t);
393       } catch (NullPointerException e) {
394         return false;
395       } catch (ClassCastException e) {
396         return false;
397       }
398     }
399 
400     @Override public boolean equals(@Nullable Object obj) {
401       if (obj instanceof InPredicate) {
402         InPredicate<?> that = (InPredicate<?>) obj;
403         return target.equals(that.target);
404       }
405       return false;
406     }
407 
408     @Override public int hashCode() {
409       return target.hashCode();
410     }
411 
412     @Override public String toString() {
413       return "Predicates.in(" + target + ")";
414     }
415     private static final long serialVersionUID = 0;
416   }
417 
418   /** @see Predicates#compose(Predicate, Function) */
419   private static class CompositionPredicate<A, B>
420       implements Predicate<A>, Serializable {
421     final Predicate<B> p;
422     final Function<A, ? extends B> f;
423 
424     private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) {
425       this.p = checkNotNull(p);
426       this.f = checkNotNull(f);
427     }
428 
429     @Override
430     public boolean apply(@Nullable A a) {
431       return p.apply(f.apply(a));
432     }
433 
434     @Override public boolean equals(@Nullable Object obj) {
435       if (obj instanceof CompositionPredicate) {
436         CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj;
437         return f.equals(that.f) && p.equals(that.p);
438       }
439       return false;
440     }
441 
442     @Override public int hashCode() {
443       return f.hashCode() ^ p.hashCode();
444     }
445 
446     @Override public String toString() {
447       return p.toString() + "(" + f.toString() + ")";
448     }
449 
450     private static final long serialVersionUID = 0;
451   }
452 
453   private static <T> List<Predicate<? super T>> asList(
454       Predicate<? super T> first, Predicate<? super T> second) {
455     // TODO(kevinb): understand why we still get a warning despite @SafeVarargs!
456     return Arrays.<Predicate<? super T>>asList(first, second);
457   }
458 
459   private static <T> List<T> defensiveCopy(T... array) {
460     return defensiveCopy(Arrays.asList(array));
461   }
462 
463   static <T> List<T> defensiveCopy(Iterable<T> iterable) {
464     ArrayList<T> list = new ArrayList<T>();
465     for (T element : iterable) {
466       list.add(checkNotNull(element));
467     }
468     return list;
469   }
470 }
471